package com.cloud.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * @version v1.0
 * @author: TianXiang
 * @description:
 * @date: 2020/10/25
 */
public class FileUtils {
    private static final Logger LOG = LoggerFactory.getLogger(FileUtils.class.getName());

    public static String getMovieFilePath(MultipartFile file, String uuidDirPath) {
        return  String.format("%s%s%s%s%s",
                uuidDirPath,
                File.separator,
                "temp",
                ".",
                file.getOriginalFilename().split("\\.")[1]);
    }

    public static String getMovieFilePath(String fileName, String uuidDirPath) {
        return  String.format("%s%s%s%s%s",
                uuidDirPath,
                File.separator,
                "temp",
                ".",
                fileName.split("\\.")[1]);
    }

    /**
     * MultipartFile 转 File
     * @param uuidDirPath : 保存文件的路径
     */
    public static File multipartFileToFile(MultipartFile file, String uuidDirPath, String movieFilePath) {
        File toFile = null;
        InputStream is = null;
        try {
            File uuidDir = new File(uuidDirPath);
            if(!uuidDir.exists()) {
                uuidDir.mkdirs();
            }
            is = file.getInputStream();

            toFile = new File(movieFilePath);
            inputStreamToFile(is, toFile);
        } catch (IOException e) {
            LOG.error(e.getMessage());
        }finally {
            try {
                is.close();
            } catch (IOException e) {}
        }
        return toFile;
    }

    //获取流文件
    private static void inputStreamToFile(InputStream is, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = is.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            is.close();
        } catch (Exception e) {
            LOG.error(e.getMessage());
        }
    }
}
